package com.gitee.leijin.rbac.controller;

import cn.hutool.core.collection.CollUtil;
import com.gitee.leijin.rbac.config.properties.AuthorizationProperties;
import com.gitee.leijin.rbac.config.properties.PropertySourceConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPattern;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/test")
public class TestController {

//    @Resource
//    private PropertySourceConfig propertySourceConfig;

    @Resource
    private AuthorizationProperties authorizationProperties;

    @Resource
    private RequestMappingHandlerMapping handlerMapping;

    @GetMapping("/test1")
    public void test1(Principal principal) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication);

    }

    @GetMapping("/white-list")
    public List<String> getAuthWhiteList() {
        return authorizationProperties.getWhiteList();
    }


    @GetMapping("/back-url-list")
    public List<String> getBackUrlList() {
        List<String> list = new ArrayList<>();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        for (RequestMappingInfo requestMappingInfo: handlerMethods.keySet()) {
            PathPatternsRequestCondition pathPatternsCondition = requestMappingInfo.getPathPatternsCondition();
            if (pathPatternsCondition == null) {
                continue;
            }
            Set<PathPattern> patterns = pathPatternsCondition.getPatterns();
            if (CollUtil.isEmpty(patterns)) {
                continue;
            }
            list.addAll(patterns.stream().map(PathPattern::getPatternString).collect(Collectors.toList()));
        }
        return list.stream().distinct().sorted().collect(Collectors.toList());
    }
}
